﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using BusinessObjects.Constants;
using BusinessServices;
using BusinessServices.Enumerates;
using Core.Utilities;
using DataEntities;

namespace CarLeaseManageSystem
{
    public partial class FormCarMana : Form
    {
        private readonly CarService _carService;
        private readonly ChuZuService _chuZuService;
        private readonly YuZuService _yuZuService;
        private readonly WeiZhangService _weiZhangService;
        //缓存车辆信息
        private List<CarInfo> _carInfoCache = new List<CarInfo>();

        public FormCarMana()
        {
            _carService = new CarService();
            _chuZuService = new ChuZuService();
            _yuZuService = new YuZuService();
            _weiZhangService = new WeiZhangService();
            InitializeComponent();
        }


        //初始化窗口
        private void FormCarMana_Load(object sender, EventArgs e)
        {
        }

        //当切换标签时响应
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabExistCar)
            {
                CacheCarInfo();
                LoadListView();
            }
        }

        //加载列表
        private void CacheCarInfo()
        {
            _carInfoCache = _carService.GetAll();
        }

        // 加载已有车辆列表视图
        private void LoadListView()
        {
            listViewExist.Items.Clear();
            var carStatus = (CarStatus)comBoxArea.SelectedIndex;
            if (carStatus == CarStatus.All)
            {
                _carInfoCache.ForEach(LoadListItems);
                return;
            }
            if (carStatus == CarStatus.IsUsing)
            {
                _carInfoCache.Where(c => !c.bBF).ToList().ForEach(LoadListItems);
                return;
            }
            if (carStatus == CarStatus.IsScrap)
            {
                _carInfoCache.Where(c => c.bBF).ToList().ForEach(LoadListItems);
            }
        }

        //加载已有车辆列表视图
        private void LoadListItems(CarInfo carInfo)
        {
            ListViewItem cLi = new ListViewItem();
            cLi.Text = carInfo.sCType;
            cLi.Tag = carInfo.iCarid;
            cLi.SubItems.Add(carInfo.sCPId);
            cLi.SubItems.Add(carInfo.bBF.ToString());
            listViewExist.Items.Add(cLi);
        }

        //保存
        private void btnNewSave_Click(object sender, EventArgs e)
        {
            if (txtBoxNewCar.Text == "" || txtBoxNewCPId.Text == "" || txtBoxNewCJId.Text == "" || txtBoxNewCJId.Text == "" || txtBoxNewYQId.Text == "")
            {
                MessageBox.Show(NewCarConstant.CarInfoNotFull, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var imgBuffer = pictBoxNewCarPhoto.Image.ToBinary();

            var newCar = new CarInfo
            {
                sCType = txtBoxNewCar.Text,
                sCPId = txtBoxNewCPId.Text,
                sCJId = txtBoxNewCJId.Text,
                sEngineId = txtBoxNewYQId.Text,
                mCPhoto = imgBuffer,
                tBFDate = DateTime.Now.AddYears(14)
            };

            newCar = _carService.Add(newCar);

            if (newCar != null && newCar.iCarid > 0)
            {
                MessageBox.Show(NewCarConstant.AddCarSucceed, "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnReset_Click(sender, e);
            }
            else
            {
                MessageBox.Show(NewCarConstant.AddCarFailed, "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //重置
        private void btnReset_Click(object sender, EventArgs e)
        {
            txtBoxNewCar.Text = txtBoxNewCPId.Text = txtBoxNewCJId.Text = txtBoxNewCJId.Text = txtBoxNewYQId.Text = "";
            pictBoxNewCarPhoto.Image = Properties.Resources.car2;
        }

        //上传照片
        private void btnUpLoadCar_Click(object sender, EventArgs e)
        {
            openFilePict.FileName = string.Empty;
            openFilePict.Filter = "jpg格式文件|*.jpg|bmp格式文件|*.bmp|gif格式文件|*.gif";
            if (openFilePict.ShowDialog() == DialogResult.OK)
            {
                Image img = Bitmap.FromStream(openFilePict.OpenFile());
                pictBoxNewCarPhoto.Image = img.Resize(pictBoxNewCarPhoto.Width, pictBoxNewCarPhoto.Height);
            }
            else
            {
                //如果没有选择图片,则加载默认的图片
                pictBoxNewCarPhoto.Image = Properties.Resources.car2;
            }
        }

        //根据车辆状态查看
        private void comBoxArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadListView();
        }

        //当搜索条件更改时触发搜索
        private void txtBoxSearCar_TextChanged(object sender, EventArgs e)
        {
            //得到用户输入内容
            var key = txtBoxSearCar.Text.ToLower();

            //清空车辆列表信息
            listViewExist.Items.Clear();

            //根据车型或车牌模糊查询
            _carInfoCache.Where(c => c.sCType.ToLower().Contains(key) || c.sCPId.ToLower().Contains(key)).ToList().ForEach(LoadListItems);
        }

        //当单击列表视图项时显示车辆详细信息
        private void listViewExist_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if(!e.IsSelected)
            {
                return;
            }
            var carId = (int)e.Item.Tag;
            var carInfo = _carInfoCache.First(c => c.iCarid == carId);
            ShowCarDetail(carInfo);

            var cz = _chuZuService.GetSimpleChuZuInfoByCarId(carId);
            var yz = _yuZuService.GetSimpleYuZuInfoByCarId(carId);
            var wz = _weiZhangService.GetSimpleWeiZhangInfoByCarId(carId);

            txtBoxLeaseInfo.Text = cz.Content + yz.Content;
            txtBoxWZ.Text = wz.Content;
            labLeased.Text = string.Format("出租[{0}]条 预租[{1}]条", cz.Count, yz.Count);
            labWZ.Text = String.Format("共[{0}]条 未处理[{1}]条", wz.Count, wz.Unsettled);
        }

        //将车辆详细信息写入相应到控件
        private void ShowCarDetail(CarInfo carInfo)
        {
            txtBoxCX.Text = carInfo.sCType;
            txtBoxCPId.Text = carInfo.sCPId;
            txtBoxCJId.Text = carInfo.sCJId;
            txtBoYQId.Text = carInfo.sEngineId;
            dateTimeBF.Value = carInfo.tBFDate;
            pictBoxCar.Image = carInfo.mCPhoto.ToImage();
            comBoxBF.Text = carInfo.bBF ? "是" : "否";
            btnEdit.Tag = carInfo.iCarid;
        }

        //保存详细信息更新
        private void SaveEdit()
        {
            var carId = (int)btnEdit.Tag;
            _carService.Update(carId, DoUpdate);
        }

        //此委托方法执行更新
        private void DoUpdate(CarInfo carInfo)
        {
            carInfo.sCType = txtBoxCX.Text;
            carInfo.sCPId = txtBoxCPId.Text;
            carInfo.sCJId = txtBoxCJId.Text;
            carInfo.sEngineId = txtBoYQId.Text;
            carInfo.tBFDate = dateTimeBF.Value.Date;
            carInfo.bBF = comBoxBF.Text == "是";
        }

        //编辑
        private void btnEdit_Click(object sender, EventArgs e)
        {
            txtBoxCX.ReadOnly = txtBoxCPId.ReadOnly = txtBoxCJId.ReadOnly = txtBoYQId.ReadOnly = false;
            comBoxBF.Enabled = dateTimeBF.Enabled = true;
            if (btnEdit.Text == "保存")
            {
                SaveEdit();
                txtBoxCX.ReadOnly = txtBoxCPId.ReadOnly = txtBoxCJId.ReadOnly = txtBoYQId.ReadOnly = true;
                comBoxBF.Enabled = dateTimeBF.Enabled = false;
                btnEdit.Text = "编辑";
                CacheCarInfo();
                LoadListView();
                return;
            }
            btnEdit.Text = "保存";
        }

        private void txtBoxNewCPId_TextChanged(object sender, EventArgs e)
        {
            if (txtBoxNewCPId.Text.Length > 7)
            {
                MessageBox.Show(NewCarConstant.CPIdError, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBoxNewCPId.Text = txtBoxNewCPId.Text.Substring(0, 7);
                this.Controls.Find("txtBoxNewCJId", true)[0].Focus();
            }
            else
                labCP.Text = "[" + txtBoxNewCPId.Text.Length + "/07]";
        }

        private void txtBoxNewCJId_TextChanged(object sender, EventArgs e)
        {

            if (txtBoxNewCJId.Text.Length > 17)
            {
                MessageBox.Show(NewCarConstant.CJIdError, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtBoxNewCJId.Text = txtBoxNewCJId.Text.Substring(0, 17);
                this.Controls.Find("txtBoxNewYQId", true)[0].Focus();

            }
            else
                labCJ.Text = "[" + txtBoxNewCJId.Text.Length + "/17]";
        }

        private void txtBoxNewCPId_Leave(object sender, EventArgs e)
        {
            if (txtBoxNewCPId.Text.Length < 7)
            {
                if (MessageBox.Show(NewCarConstant.CPIdError, "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
                    txtBoxNewCPId.Focus();
                else
                    this.Close();
            }
        }

        private void txtBoxNewCJId_Leave(object sender, EventArgs e)
        {
            if (txtBoxNewCJId.Text.Length < 17)
            {
                if (MessageBox.Show(NewCarConstant.CJIdError, "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
                    txtBoxNewCJId.Focus();
                else
                    this.Close();
            }
        }

    }
}
